package cn.zero.filter;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

@Component
public class LoginFilter extends ZuulFilter {
    // filter类型
    @Override
    public String filterType() {
        return "pre";
    }

    // filter的执行顺序
    @Override
    public int filterOrder() {
        return 0;
    }
    // 是否执行run方法
    @Override
    public boolean shouldFilter() {
        //获取请求
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        //获取url
        String requestURI = request.getRequestURI();
        //判断请求中是否有login/register结尾
        if (requestURI.endsWith("login")||requestURI.endsWith("register")){
            return false;
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //获取请求
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        //获取请求头中token
        String token = request.getHeader("token");

        //获取响应
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
        //设置格式字符集
        response.setContentType("application/json;charset=utf-8");

        //判断token是否为空
        if (StringUtils.isEmpty(token)){
            try {
                //为空响应提示{
                PrintWriter writer = null;
                writer = response.getWriter();
                HashMap<String, Object> map = new HashMap<>();
                map.put("success", false);
                map.put("message", "请登录！");
                map.put("obj","noLogin");
                String data = JSONObject.toJSONString(map);
                writer.write(data);
                RequestContext.getCurrentContext().setSendZuulResponse(false);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        return null;
    }
}
